﻿using System;
using System.Threading.Tasks;
using FreeRedis;

namespace LeoGemini.Service.Infrastructure.Extension
{
    public static partial class Extensions
    {
        /// <summary>
        /// 从缓存或数据库中获取对象
        /// </summary>
        public static async Task<TEntity> CacheOrGetAsync<TEntity>(this RedisClient client, 
            string cacheKey, Func<Task<TEntity>> action, int expire = 0)
        {
            var data = client.Get<TEntity>(cacheKey);
            
            if (data == null)
            {
                data = await action();
                if (data != null)
                {
                    client.Set(cacheKey, data, expire);
                }
            }

            return data;
        }

        /// <summary>
        /// 删除缓存，并更新数据库
        /// </summary>
        /// <param name="action">
        /// 获取缓存后的操作，注：redis中查询到的聚合根子实体不会被ef core自动变更追踪，之后的更新操作只能更新到聚合根，而不会更新子实体。
        /// 因此需要在action中进行手动追踪实体变更。
        /// </param>
        public static async Task RemoveAndPersistAsync(this RedisClient client, 
            Func<Task> action, params string[] cacheKeys)
        {
            await action();
            client.Del(cacheKeys);
        }
    }
}